package cn.shyouchi.wuguanjia.android.ui.event.proprietor;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.jeanboy.cropview.cropper.CropperHandler;
import com.jeanboy.cropview.cropper.CropperManager;
import com.jeanboy.cropview.cropper.CropperParams;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.event.EventApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.controls.BasicEditDialogFragment;
import cn.shyouchi.wuguanjia.android.event.DataChangeEvent;
import cn.shyouchi.wuguanjia.android.impl.ModuleItemClickListener;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.model.OwnerEntity;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


@RuntimePermissions
public class AddProprietorActivity extends BaseActivity implements
        CropperHandler, ModuleItemClickListener<ProprietorInfoModel> {
    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.rv_proprietor_info)
    RecyclerView mRvProprietorInfo;
    ProprietorInfoAdapter mAdapter;
    List<ProprietorInfoModel> mModels = new ArrayList<>();
    ProprietorInfoModel headerModel;
    OwnerEntity.ProprietorBean proprietor;
    boolean isEdit;

    String projectId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CropperManager.getInstance().build(this);
    }

    @Override
    public int initContentView() {
        return R.layout.activity_add_proprietor;
    }

    @Override
    public void initInjector() {
        proprietor = getIntent().getParcelableExtra("proprietor");
        projectId = getIntent().getStringExtra("projectId");

    }


    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        mTopBar.setTitle(getTitle().toString());
        setSupportActionBar(mTopBar.getToolbar());
        mRvProprietorInfo.setLayoutManager(new LinearLayoutManager(mContext));

        if (proprietor != null) {
            isEdit = true;
            ToastUtil.showToast("编辑状态");
            initModel(proprietor);
        } else {
            initModel();
        }

        mAdapter = new ProprietorInfoAdapter(mModels, this);
        mRvProprietorInfo.setAdapter(mAdapter);
    }

    private void initModel() {
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_AVATAR, "头像", "请输入业主头像", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, false));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_NAME, "姓名", "请输入业主姓名", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_GENDER, "性别", ProprietorInfoModel.EDIT_TYPE_SEL, new String[]{"男", "女"}, true));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_AGE, "年龄", "请输入业主年龄", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_NUMBER, false, true));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_HEIGHT, "身高", "请输入业主身高", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_NUMBER, false, true));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_DUTY, "职务", "请输入业主职务", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_WORK_TIME, "工作时间", "如：09:00-17:00", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_PLATE, "车牌号", "如：沪A88888", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_PHONE, "手机号", "请输入业主手机号", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_NUMBER, false, true));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_OTHER, "其他", "请输入其他信息", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, true, false));
    }


    private void initModel(OwnerEntity.ProprietorBean proprietor) {
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_AVATAR, "头像", "请输入业主头像", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, false, proprietor.getImages()));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_NAME, "姓名", "请输入业主姓名", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true, proprietor.getName()));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_GENDER, "性别", ProprietorInfoModel.EDIT_TYPE_SEL, new String[]{"男", "女"}, true, proprietor.getInfo().getSex()));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_AGE, "年龄", "请输入业主年龄", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_NUMBER, false, true, String.valueOf(proprietor.getInfo().getAge())));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_HEIGHT, "身高", "请输入业主身高", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_NUMBER, false, true, String.valueOf(proprietor.getInfo().getHeight())));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_DUTY, "职务", "请输入业主职务", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true, proprietor.getInfo().getJob()));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_WORK_TIME, "工作时间", "如：09:00-17:00", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true, proprietor.getInfo().getWorkinghours()));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_PLATE, "车牌号", "如：沪A88888", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, false, true, proprietor.getInfo().getNumberplates()));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_PHONE, "手机号", "请输入业主手机号", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_NUMBER, false, true, String.valueOf(proprietor.getInfo().getPhone())));
        mModels.add(new ProprietorInfoModel(ProprietorInfoModel.INFO_TYPE_OTHER, "其他", "请输入其他信息", ProprietorInfoModel.EDIT_TYPE_FILL, InputType.TYPE_CLASS_TEXT, true, false, proprietor.getInfo().getRemarks()));
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    private synchronized void showFieldEditDialog(final ProprietorInfoModel model) {
        BasicEditDialogFragment dialog = BasicEditDialogFragment.newInstance(model.getName(), model.getHint(), model.getInputType(), model.isMultiLines());
        dialog.setEnterClickListener(new BasicEditDialogFragment.BasicEditDialogListener() {
            @Override
            public void onBasicEditDialogPositiveClick(DialogFragment dialog, String content) {
                model.setValue(content);
                mAdapter.notifyDataSetChanged();
            }
        });
        dialog.show(getFragmentManager(), "CompanyEditDialogFragment");
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE|WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

    }

    private synchronized void showSetTimeDialog(final ProprietorInfoModel model) {
        ArrangeTimeSetDialog dialog = ArrangeTimeSetDialog.newInstance();
        dialog.setClickListener(new ArrangeTimeSetDialog.ArrangeTimeSetDialogListener() {
            @Override
            public void onPositiveClick(DialogFragment dialog, String content) {
                model.setValue(content);
                mAdapter.notifyDataSetChanged();
            }
        });
        dialog.show(getFragmentManager(), "CompanyEditDialogFragment");
    }

    private synchronized void showSelDialog(final ProprietorInfoModel model) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText(model.getName());
        builder.setCustomTitle(tvTitle);
        builder.setItems(model.getOptions(), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                model.setValue(String.valueOf(which + 1));
                dialog.dismiss();
                mAdapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }

    private synchronized void showSelHeaderDialog(final ProprietorInfoModel model) {
        headerModel = model;
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText("设置头像");
        builder.setCustomTitle(tvTitle);
        builder.setItems(new String[]{"拍照", "相册"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        AddProprietorActivityPermissionsDispatcher.pickFromCameraWithCheck(AddProprietorActivity.this);
                        break;
                    case 1:
                        AddProprietorActivityPermissionsDispatcher.pickFromGalleryWithCheck(AddProprietorActivity.this);
                        break;
                }
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.add("保存");
        menuItem.setShowAsAction(2);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getTitle().equals("保存")) {
            generateProprietor(this.mModels);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void generateProprietor(List<ProprietorInfoModel> models) {
        boolean filledAll = true;
        ProprietorEntity entity = new ProprietorEntity();
        for (ProprietorInfoModel model : models) {
            if (model.isNotNull()) {
                if (model.isFilled()) {
                    switch (model.getType()) {
                        case ProprietorInfoModel.INFO_TYPE_AVATAR:
                            entity.setAvatarPath(model.getValue());
                            break;
                        case ProprietorInfoModel.INFO_TYPE_NAME:
                            entity.setName(model.getValue());
                            break;
                        case ProprietorInfoModel.INFO_TYPE_AGE:
                            entity.setAge(model.getValue());
                            break;
                        case ProprietorInfoModel.INFO_TYPE_GENDER:
                            entity.setGender(model.getValue());
                            break;
                        case ProprietorInfoModel.INFO_TYPE_HEIGHT:
                            entity.setHeight(model.getValue());
                            break;
                        case ProprietorInfoModel.INFO_TYPE_DUTY:
                            entity.setDuty(model.getValue());
                            break;
                        case ProprietorInfoModel.INFO_TYPE_WORK_TIME:
                            entity.setWorkTime(model.getValue());
                            break;
                        case ProprietorInfoModel.INFO_TYPE_PLATE:
                            entity.setPlate(model.getValue());
                            break;
                        case ProprietorInfoModel.INFO_TYPE_PHONE:
                            entity.setPhone(model.getValue());
                            break;
                        case ProprietorInfoModel.INFO_TYPE_OTHER:
                            entity.setOther(model.getValue());
                            break;
                    }
                } else {
                    filledAll = false;
                    model.setFillError();
                }
            } else {
                switch (model.getType()) {
                    case ProprietorInfoModel.INFO_TYPE_AVATAR:
                        entity.setAvatarPath(model.getValue());
                        break;
                    case ProprietorInfoModel.INFO_TYPE_NAME:
                        entity.setName(model.getValue());
                        break;
                    case ProprietorInfoModel.INFO_TYPE_AGE:
                        entity.setAge(model.getValue());
                        break;
                    case ProprietorInfoModel.INFO_TYPE_GENDER:
                        entity.setGender(model.getValue());
                        break;
                    case ProprietorInfoModel.INFO_TYPE_HEIGHT:
                        entity.setHeight(model.getValue());
                        break;
                    case ProprietorInfoModel.INFO_TYPE_DUTY:
                        entity.setDuty(model.getValue());
                        break;
                    case ProprietorInfoModel.INFO_TYPE_WORK_TIME:
                        entity.setWorkTime(model.getValue());
                        break;
                    case ProprietorInfoModel.INFO_TYPE_PLATE:
                        entity.setPlate(model.getValue());
                        break;
                    case ProprietorInfoModel.INFO_TYPE_PHONE:
                        entity.setPhone(model.getValue());
                        break;
                    case ProprietorInfoModel.INFO_TYPE_OTHER:
                        entity.setOther(model.getValue());
                        break;

                }
            }
        }

        if (filledAll) {
            EventApi eventApi = new EventApi(mContext);

            if (isEdit) {

                entity.setId(String.valueOf(proprietor.getId()));
                eventApi.upOwner(projectId, entity)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                            @Override
                            public void onNext(BaseRequestResult entity) {
                                EventBus.getDefault().post(new DataChangeEvent());
                                finish();
                            }
                        });
            } else {
                eventApi.addOwner(projectId, entity)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new ProgressSubscriber<BaseRequestResult>(mContext) {
                            @Override
                            public void onNext(BaseRequestResult entity) {
                                setResult(EventProprietorActivity.REQUEST_TYPE_ADD_PROPRIETOR_SUCCESS);
                                finish();
                            }
                        });
            }


        } else {
            ToastUtil.showToast("信息不完整");
            mAdapter.notifyDataSetChanged();
        }


    }


    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void pickFromCamera() {
        CropperManager.getInstance().pickFromCamera();
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void pickFromGallery() {
        CropperManager.getInstance().pickFromGallery();
    }


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public CropperParams getParams() {
        return new CropperParams(856, 856);
    }

    @Override
    public void onCropped(Uri uri) {

        LogUtil.e(uri.toString());

        if (headerModel != null) {
            headerModel.setValue(uri.getPath());
            mAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onCropCancel() {

    }

    @Override
    public void onCropFailed(String msg) {
        ToastUtil.showToast(msg);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        CropperManager.getInstance().handlerResult(requestCode, resultCode, data);
    }

    /*-------------------权限处理-----------------*/
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AddProprietorActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void showRationaleForCamera(PermissionRequest request) {
        showRationaleDialog("该操作需要使用摄像头，请允许！", request);
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void showRationaleForPick(PermissionRequest request) {//权限说明
        showRationaleDialog("该操作需要操作内存卡，请允许！", request);
    }


    private void showRationaleDialog(String msg, final PermissionRequest request) {
        new android.support.v7.app.AlertDialog.Builder(getActivity())
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage(msg)
                .show();
    }

    @Override
    public void moduleItemClick(ProprietorInfoModel model) {
        if (model.getType() == ProprietorInfoModel.INFO_TYPE_AVATAR) {
            showSelHeaderDialog(model);
            return;
        } else if (model.getType() == ProprietorInfoModel.INFO_TYPE_WORK_TIME) {
            showSetTimeDialog(model);
            return;
        }

        switch (model.getEditType()) {
            case ProprietorInfoModel.EDIT_TYPE_FILL:
                showFieldEditDialog(model);
                break;
            case ProprietorInfoModel.EDIT_TYPE_SEL:
                showSelDialog(model);
                break;
        }
    }

    @Override
    public void moduleItemLongClick(ProprietorInfoModel model) {

    }

    @Override
    public void onDel(ProprietorInfoModel model) {

    }
}
